<template>
    <el-select v-model="selectValue" placeholder="选择分类" @change="onChange">
        <el-option v-for="item in categorySelect" :key="item.id" :label="item.title" :style="selectOptStyle(item)" :value="item.id">
        </el-option>
    </el-select>
</template>

<script>
import tree from '@/modules/plugins/tree-data';

export default {
    name: 'catsSelect',
    props: ['value', 'change'],
    data() {
        return {
            selectValue: this.value,
            categorySelect: [],
            categoryObj: {},
            categoryTree: []
        };
    },
    watch: {
        value(newValue) {
            this.selectValue = newValue;
        }
    },
    methods: {
        init(data) {
            let categoryTree = tree(data),
                catArr = [categoryTree];
            this.categorySelect = [];
            this.categoryObj = {};
            this.getSelect(catArr);
            this.categoryTree = categoryTree.children;
        },
        getSelect(data) {
            for (let i = 0; i < data.length; i++) {
                this.categorySelect.push({
                    id: data[i].id,
                    title: data[i].title,
                    level: data[i].path.split(',').length
                });

                this.categoryObj[data[i].id] = data[i];

                if (data[i].children) {
                    if (data[i].children.length > 0) {
                        this.getSelect(data[i].children);
                    }
                }
            }
        },
        // select option 缩进
        selectOptStyle(item) {
            return {
                'padding-left': item.level * 8 + 'px'
            };
        },
        onChange() {
            this.change(this.selectValue);
        }
    }
};
</script>
